package com.pinkmeet.dao;

import com.pinkmeet.bean.Message;
import com.pinkmeet.util.DBUtil;

import java.sql.*;
import java.sql.Date;
import java.util.*;

/**
 * Created by mars on 2018/5/9.
 */
public class MessagesDAO {
    private Connection conn;

    public MessagesDAO(){
        conn = DBUtil.getConnection();
    }

    //返回message数组
    public ArrayList<Message> getMessagesById(int id){
        ArrayList<Message> messages = new ArrayList<>();
        String sql = "SELECT * FROM messages WHERE cid = ? OR ccid = ? ORDER send_time ";
        PreparedStatement pstmt = null;
        try {
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,id);
            pstmt.setInt(2,id);
            ResultSet res = pstmt.executeQuery();
            if (res.next()){
                Message message = new Message();
                message.setId(res.getInt("id"));
                message.setCid(res.getInt("cid"));
                message.setCcid(res.getInt("ccid"));
                message.setContent(res.getString("content"));
                message.setTime(res.getDate("time"));
                messages.add(message);
            }

        }catch (SQLException e){
            e.printStackTrace();
        }

        return messages;
    }

    public  boolean saveMessage(int cid, int ccid, String content, java.util.Date time){
        String sql = "INSERT INTO messages (cid,ccid,content,send_time) VALUES (?,?,?,?)";
        PreparedStatement pstmt = null;
        try{
            pstmt = this.conn.prepareStatement(sql);
            pstmt.setInt(1,cid);
            pstmt.setInt(2,ccid);
            pstmt.setString(3,content);
            pstmt.setDate(4, (Date) time);
            pstmt.execute();
            return true;
        }catch (SQLException e){
            e.printStackTrace();
        }

        return false;
    }

}
